//
//  LLStatusPictureView.swift
//  WeiBoShiBing
//
//  Created by Bingo on 15/11/1.
//  Copyright © 2015年 Bingo. All rights reserved.
//

import UIKit
import SDWebImage
//cell加载微博图片
let  LLStatusPictureViewCellSelectedPictureNotification = "LLStatusPictureViewCellSelectedPictureNotification"

let LLStatusPictureViewCellSelectedPictureURLKey = "LLStatusPictureViewCellSelectedPictureURLKey"

let LLStatusPictureViewCellSelectedPictureIndexKey = "LLStatusPictureViewCellSelectedPictureIndexKey"

let LLStatusPictureViewCellSelectedPictureModelKey =
    "LLStatusPictureViewCellSelectedPictureModelKey"

class LLStatusPictureView: UICollectionView {
    
    private let StatusPictureViewIdentifier = "StatusPictureViewIdentifier"
    
    var status:LLStatus?{
        didSet{
            
            //            sizeToFit()
            reloadData()
        }
        
    }
    // 这个方法是 sizeToFit调用的,而且 返回的 CGSize 系统会设置为当前view的size
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    
    func calcViewSize() -> CGSize{
        let itemSize = CGSize(width: 90, height: 90)
        
        pictureLayout.itemSize = itemSize
        pictureLayout.minimumInteritemSpacing = 0
        pictureLayout.minimumLineSpacing = 0
        
        
        let margin:CGFloat = 10
        
        let column = 3
        
        let count = status?.pic_urls?.count ?? 0
        if count == 0 {
            
            return CGSizeZero
        }
        
        if count == 1{
            
            let urlString = status!.pictureURLs![0].absoluteString
            
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString)
            
            
            var size = CGSize(width: 150, height: 120)
            
            if image != nil{
                size = image.size
            }
            if image.size.width < 40{
                
                size.width = 40
            }
            
            
            pictureLayout.itemSize = size
            return size
        }
        pictureLayout.minimumLineSpacing = margin
        pictureLayout.minimumLineSpacing = margin
        
        if count == 4 {
            let width = 2 * itemSize.width + margin
            
            return CGSize(width: width, height: width)
        }
        
        
        let row = (count + column - 1) / column
        
        let widht = (CGFloat(column) * itemSize.width) + (CGFloat(column) - 1) * margin
        
        let height = (CGFloat(row) * itemSize.height) + (CGFloat(row) - 1) * margin
        
        return CGSize(width: widht, height: height)
    }
    
    init() {
        super.init(frame: CGRectZero, collectionViewLayout: pictureLayout)
        
        dataSource = self
        
        delegate = self 
        backgroundColor = UIColor.clearColor()
        
        registerClass(LLStatusPicturViewCell.self, forCellWithReuseIdentifier: StatusPictureViewIdentifier)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private var pictureLayout = UICollectionViewFlowLayout()
    
}

extension LLStatusPictureView:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureViewIdentifier, forIndexPath: indexPath) as!LLStatusPicturViewCell
        
        //        let url = status?.pic_urls?[indexPath.row]["thumbnail_pic"] as? String
        //        cell.imageURL = NSURL(string: url!)
        cell.imageURL = status?.pictureURLs?[indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        print("cell点击了")
        
        var models = [LLPhotoBrowserModel]()
        
        let count = status?.largePictureURLs?.count ?? 0
        
        for i in 0..<count{
            
            let model = LLPhotoBrowserModel()
            
            let url = status?.largePictureURLs?[i]
            
            let cell = collectionView.cellForItemAtIndexPath(NSIndexPath(forItem: i, inSection: 0)) as!LLStatusPicturViewCell
            
            let imageView = cell.iconView
            
            model.url = url
            model.imageView = imageView
            models.append(model)
        }
    
        let userInfo: [String: AnyObject] = [
//            LLStatusPictureViewCellSelectedPictureURLKey: status!.largePictureURLs,
//            LLStatusPictureViewCellSelectedPictureIndexKey: indexPath.item
            LLStatusPictureViewCellSelectedPictureModelKey:models,LLStatusPictureViewCellSelectedPictureIndexKey:indexPath.item
        ]
        
        NSNotificationCenter.defaultCenter().postNotificationName(LLStatusPictureViewCellSelectedPictureNotification, object: self, userInfo: userInfo)
    }
    
}
class LLStatusPicturViewCell:UICollectionViewCell{
    
    var imageURL:NSURL?{
        didSet{
            iconView.LL_setImageWithURL(imageURL)
            
            let gif = (imageURL!.absoluteString as NSString).pathExtension.lowercaseString == "git"
            
            gitImageView.hidden = !gif
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame:frame)
        
        prepareUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func prepareUI(){
        contentView.addSubview(iconView)
        contentView.addSubview(gitImageView)
        
        iconView.ff_Fill(contentView)
        gitImageView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: contentView, size: nil)
    }
    private lazy var iconView : UIImageView = {
        let imageView = UIImageView()
        
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        
        imageView.clipsToBounds = true
        
        return imageView
    }()
    
    private lazy var gitImageView:UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
}
